package com.androidhive.dashboard;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidhive.dashboard.R;



public class View_Teams_Activity extends Activity implements OnItemClickListener 
{
	
	  private ListView mainListView ;
	  private ArrayAdapter<String> listAdapter ;
	  private ProgressDialog pDialog;
	  public static Boolean isOpen=false;

	  // Creating JSON Parser object
	  JSONParser jParser = new JSONParser();

	  ArrayList<String> emailsList;

	  // url to get all products list
	  private static String url_team_ids = "http://i-com.co.ug/ufollo/get_team_ids_for_dee.php";
	  
	  private static final String TAG_SUCCESS = "success";
	  private static final String TAG_PRODUCTS = "team_name";
	  private static final String TAG_TEAM = "team_name";
	  
	  JSONArray inbox_messages = null;
	  
	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewteams);

     // Hashmap for ListView
		emailsList = new ArrayList<String>();

		// Loading products in Background Thread
		new LoadAllProducts().execute();
		
        // Find the ListView resource. 
        mainListView = (ListView) findViewById( R.id.mainListView );
        

        // Create and populate a List of planet names.
//        String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
//                                          "Jupiter", "Saturn", "Uranus", "Neptune"};  
//        ArrayList<String> planetList = new ArrayList<String>();
//        planetList.addAll( Arrays.asList(planets) );
        
        // Create ArrayAdapter using the planet list.
//       listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
        
//        // Add more planets. If you passed a String[] instead of a List<String> 
//        // into the ArrayAdapter constructor, you must not add more items. 
//        // Otherwise an exception will occur.
//        listAdapter.add( "Ceres" );
//        listAdapter.add( "Pluto" );
//        listAdapter.add( "Haumea" );
//        listAdapter.add( "Makemake" );
//        listAdapter.add( "Eris" );

        
        // Set the ArrayAdapter as the ListView's adapter.
//      mainListView.setAdapter( listAdapter );
        
        mainListView.setOnItemClickListener(this);
    }
    public void loadlistView() {
    	ArrayAdapter<String> arrayAdapter =      
		        new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, emailsList);
    	mainListView.setAdapter( arrayAdapter );
		
	}
    /**
	 * Background Async Task to Load all product by making HTTP Request
	 * */
	class LoadAllProducts extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(View_Teams_Activity.this);
			pDialog.setMessage("Loading clients... Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) {
			
//			String query_variable = MyApplication.getLoginVariable();
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("team_name", " "));
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_team_ids, "GET", params);
			
			// Check your log cat for JSON reponse
			Log.d("All Client Business Data: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) 
				{
					// products found
					// Getting Array of Products
					inbox_messages = json.getJSONArray(TAG_PRODUCTS);

					// looping through All Products
					for (int i = 0; i < inbox_messages.length(); i++) 
					{
						JSONObject c = inbox_messages.getJSONObject(i);

						// Storing each json item in variable
						String team = c.getString(TAG_TEAM);

						

						// creating new HashMap
					

						// adding HashList to ArrayList
						emailsList.add(team);
					}
				}
				else 
				{
					// no products found
					// Launch Add New product Activity
					Intent i = new Intent(getApplicationContext(),
							View_Teams_Activity.class);
					// Closing all previous activities
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
			} 
			catch (JSONException e) 
			{
				e.printStackTrace();
				Log.e("crash!", e.getMessage());
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			loadlistView();
			// updating UI from Background Thread
			
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) 
	{
		// TODO Auto-generated method stub
		String item = adapter.getItemAtPosition(position).toString();
		Intent view_concept = new Intent(this, View_Concept_Activity.class);
		view_concept.putExtra("team_name", item);
		startActivity(view_concept);
	}
}
